/*
********************************************************************************
* Copyright (C) 2021, xiang.D <dx_65535@163.com>.
* All right reserved.
*
* File Name   : log_add_info.h
* Author      :
* Version     : V1.0
* Description :
* Journal     : 2021-01-12 version v1.0
* Brief       : Blog: https://blog.csdn.net/qq_38750572?spm=1001.2014.3001.5343
* Others      :
                Compile command: make
********************************************************************************
*/
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/time.h>
#include "log_add_info.h"

// LEVEL_STR与sys_log.h中LOG等级定义对齐
static const char LEVEL_STR[][3] = {"E/", "W/", "D/", "I/"};  //LOG_ERR, LOG_WARN, LOG_DEBUG, LOG_INFO,
static const char TIMESTAMP_MASK[] = "%d-%02d-%02d %02d:%02d:%02d.%03ld "; // len=33
static const int  LOG_STR_LENGTH = 2000;
static int levelIndex = 0;

static int get_local_time(char *pTimeStr)
{
    struct timeval tv;
    struct tm localTimeStruct;
    int bytes = 0;

    gettimeofday( &tv, NULL );                   // Get current time
    localtime_r( &tv.tv_sec, &localTimeStruct ); // Convert time (threadsave version)

    // 2022-01-14 10:09:51.106
    bytes = sprintf(pTimeStr, TIMESTAMP_MASK,
        localTimeStruct.tm_year + 1900, localTimeStruct.tm_mon + 1, localTimeStruct.tm_mday,
        localTimeStruct.tm_hour, localTimeStruct.tm_min, localTimeStruct.tm_sec,
        tv.tv_usec / 1000
       );

    if (bytes < 0) {
        bytes = 0;
    }

    return bytes;
}

CLogAddInfo* CLogAddInfo::GetInstance(CLogBase *pLog)
{
    static CLogAddInfo obj(pLog);
    return &obj;
}

int CLogAddInfo::WriteLog(const char *tag, const char *msg)
{
    char logStr[LOG_STR_LENGTH] = {0};  // 一次log打印长度不得超过2000
    int length = 0;

    // log增加调试信息: time、level、Tag: 2022-01-14 10:09:51.106 I/ <main>
    length = get_local_time(logStr);
    snprintf(logStr + length, LOG_STR_LENGTH - length, "%s <%s> %s", LEVEL_STR[levelIndex], tag, msg);

    CCustomLog::WriteLog(tag, logStr);
    return strlen(logStr);
}

int CLogAddInfo::SetLogLevel(int level)
{
    levelIndex = level;
    CCustomLog::SetLogLevel(level);
    return 0;
}
